/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018/11/21 Time: 10:06
 *
 * 个人中心
 */

import React, {Component} from 'react';
import {
    Linking,
    SafeAreaView,
    ScrollView,
    TouchableOpacity,
    View,
    TouchableHighlight,
    Text,
    Platform,
    BackHandler,
    ToastAndroid,
    Modal,
} from 'react-native';
import {connect} from 'react-redux';
import {Row, Rows, Table} from 'react-native-table-component';
import {styles} from './StaffSchedule.Style';
import {COLOR_LINK, FONT_COLOR_SUB_TITLE, FONT_COLOR_TITLE} from "../../../constant/PHColors";
import {getDs} from "../../Housekeeper/orderScreen/Actions";
import {
    retrieveWhskShiftsSetup,
    retrieveWhskShifts,
    retrieveWHSKShiftsArrangeDefault,
    shiftsArrangeEdit, shiftsArrangeAdd, onShiftsArrangeDel, shiftsArrangeDel
} from "./Actions";
import {FetchStatus} from "../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../configuration/ReturnStatus";
import {doDisplayWarnMessage} from "../../../component/Message/Action";
import ScrollableTabView, {DefaultTabBar} from "react-native-scrollable-tab-view";
import LoadingView from "../../../component/LoadingView/LoadingView";
import {SCREEN_WIDTH} from "../../../constant/PHScreen";
import AntDesign from "react-native-vector-icons/AntDesign";
import SelectDatePlugIn from "../../custom/selectDateTime/selectDatePlugIn"
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import SelectPlaceTwoWheelPlugIn from "../../custom/selectDateTime/selectPlaceTwoWheelPlugIn";


class StaffSchedule extends Component {

    static navigationOptions = ({navigation}) => ({
        headerTitle: ``,
        headerLeft: <View><Text style={{marginLeft:15,fontSize:18,color:FONT_COLOR_TITLE}}>员工班表</Text></View>,
        headerRight: (
            <TouchableOpacity activeOpacity={0.9} onPress={navigation.getParam('submitClick')}>
                <View style={{ height: 44,paddingRight:15, flexDirection: 'row', justifyContent: 'flex-end', alignItems: 'center'}}>
                    <Text style={{fontSize: 16, color: '#212121'}}>
                        班次时间设置
                    </Text>
                </View>
            </TouchableOpacity>
        ),
    });

    // 构造
    constructor(props) {
        super(props);

        let date = new Date();
        let year = date.getFullYear().toString();
        let month = (date.getMonth()+1).toString();
        if(Number(month)<10){
            month = '0'+month
        }
        let day = date.getDate().toString();
        if(Number(day)<10){
            day = '0'+day
        }
        let opdate = year+'-'+month+'-'+day;

        // 初始状态
        this.state = {
            whskShifts:[],          //班次
            whskShifts_arrange:[],      //值班人员
            opdate:opdate,
            widthArr:[(SCREEN_WIDTH-8-50)/3,(SCREEN_WIDTH-8-50)*2/3,50],
            defaultDate:{},//地点
            dealPeopleVisible:false, //modal
            roleSelectVisible:false,
            chooseGroup:'',//选中的组别
            chooseDealPeople:[],//选中的地点
            editInfo:{},
        };
    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;


        if (nextProps.onRetrieveWhskShiftsSetup !== this.props.onRetrieveWhskShiftsSetup && nextProps.onRetrieveWhskShiftsSetup.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveWhskShiftsSetup.RETURN === ReturnStatus.Success) {
                let WhskShifts = nextProps.onRetrieveWhskShiftsSetup.DATA;
                WhskShifts.sort((a,b)=>{
                    return a.starttime.replace(":", "")-b.starttime.replace(":", "")
                });

                this.setState({
                    whskShifts:WhskShifts,
                })

                let reg = new RegExp("-","g");
                let opdate =(this.state.opdate.replace(reg,""));
                let str2 = {"arg":{"opdate":opdate,"shift":WhskShifts[0]['shift']}};
                dispatch(retrieveWHSKShiftsArrangeDefault(JSON.stringify(str2)));
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onRetrieveWhskShiftsSetup.MSG))
            }
        }

        if (nextProps.onRetrieveWhskShifts !== this.props.onRetrieveWhskShifts && nextProps.onRetrieveWhskShifts.fetchStatus === FetchStatus.Success) {
            if (nextProps.onRetrieveWhskShifts.RETURN === ReturnStatus.Success || nextProps.onRetrieveWhskShifts.RETURN ==="0") {
                let whskShifts_arrange = nextProps.onRetrieveWhskShifts.DATA;
                this.setState({
                    whskShifts_arrange:whskShifts_arrange,
                })
            }
        }

        if (nextProps.onWHSKShiftsArrangeDefault !== this.props.onWHSKShiftsArrangeDefault && nextProps.onWHSKShiftsArrangeDefault.fetchStatus === FetchStatus.Success) {
            if (nextProps.onWHSKShiftsArrangeDefault.RETURN === ReturnStatus.Success) {
                let place = nextProps.onWHSKShiftsArrangeDefault.place;

                let place_json = {};
                place.map((item,value)=>{
                    if(place_json[item.name]){
                        place_json[item.name].push(item)
                    }else{
                        place_json[item.name] = [item]
                    }
                })

                this.setState({
                    defaultDate:place_json
                })
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onWHSKShiftsArrangeDefault.MSG))
            }
        }

        if (nextProps.onShiftsArrangeEdit !== this.props.onShiftsArrangeEdit && nextProps.onShiftsArrangeEdit.fetchStatus === FetchStatus.Success) {
            if (nextProps.onShiftsArrangeEdit.RETURN === Number(ReturnStatus.Success)) {
                ToastAndroid.show(nextProps.onShiftsArrangeEdit.MSG, 500);//提示
                let reg = new RegExp("-","g");
                let opdate =(this.state.opdate.replace(reg,""));

                let str1 = opdate;
                dispatch(retrieveWhskShifts(str1));
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onShiftsArrangeEdit.MSG))
            }
        }

        if (nextProps.onShiftsArrangeDel !== this.props.onShiftsArrangeDel && nextProps.onShiftsArrangeDel.fetchStatus === FetchStatus.Success) {
            if (nextProps.onShiftsArrangeDel.RETURN === Number(ReturnStatus.Success)) {
                ToastAndroid.show(nextProps.onShiftsArrangeDel.MSG, 500);//提示
                let reg = new RegExp("-","g");
                let opdate =(this.state.opdate.replace(reg,""));

                let str1 = opdate;
                dispatch(retrieveWhskShifts(str1));
            } else {
                dispatch(doDisplayWarnMessage(nextProps.onShiftsArrangeDel.MSG))
            }
        }



    }

    // 组件渲染后调用
    componentDidMount() {
        let {dispatch} = this.props;

        this.props.navigation.setParams({"submitClick":this._submitClick});

        let reg = new RegExp("-","g");
        let opdate =(this.state.opdate.replace(reg,""));
        let str = {"where":{"startdate":opdate}};
        dispatch(retrieveWhskShiftsSetup(JSON.stringify(str)));

        let str1 = opdate;
        dispatch(retrieveWhskShifts(str1));

    }

    _submitClick=()=>{
        let _this = this;
        this.props.navigation.navigate('StaffTimeSetting',{"whskShifts":_this.state.whskShifts,"opdate":_this.state.opdate,callBack:()=>this.returnBack()});
    };

    //返回刷新
    returnBack=()=>{
        let {dispatch} = this.props;

        this.props.navigation.navigate('StaffSchedule');

        let reg = new RegExp("-","g");
        let opdate =(this.state.opdate.replace(reg,""));
        let str = {"where":{"startdate":opdate}};
        dispatch(retrieveWhskShiftsSetup(JSON.stringify(str)));

        let str1 = opdate;
        dispatch(retrieveWhskShifts(str1));
    };

    //仅刷新
    freshScreen=()=>{
        let {dispatch} = this.props;

        let reg = new RegExp("-","g");
        let opdate =(this.state.opdate.replace(reg,""));
        let str = {"where":{"startdate":opdate}};
        dispatch(retrieveWhskShiftsSetup(JSON.stringify(str)));
    };

    render() {
        let {dispatch,onRetrieveWhskShiftsSetup} = this.props;

        if (onRetrieveWhskShiftsSetup.fetchStatus === FetchStatus.Start ) {
            return <LoadingView/>
        }else{
            if (this.state.whskShifts.length>0) {
                return (
                    <SafeAreaView style={styles.container} >
                        <View style={styles.opdateView}>
                            <AntDesign name={'clockcircleo'} size={16} style={{color: '#d7d7d7', marginRight: 10}} />
                            <SelectDatePlugIn defaultDate={this.state.opdate} textStyle={styles.opdateViewStyle} dateBack={(date)=>{
                                this.setState({opdate:date});
                                let {dispatch} = this.props;
                                let reg = new RegExp("-","g");
                                let opdate =(date.replace(reg,""));
                                let str = {"where":{"startdate":opdate}};
                                dispatch(retrieveWhskShiftsSetup(JSON.stringify(str)));

                                let str1 = opdate;
                                dispatch(retrieveWhskShifts(str1));
                            }} />

                        </View>
                        <ScrollableTabView
                            tabBarUnderlineColor="#5897FE"
                            tabBarTextStyle={{
                                fontSize:16
                            }}
                            tabBarPosition='top'
                            tabBarBackgroundColor="#F2F2F2"
                            tabBarUnderlineStyle={{backgroundColor:'#5897FE',height:2}}
                            tabBarActiveTextColor="#5897FE"
                            style={styles.container}
                            renderTabBar={() => <DefaultTabBar style={{height:40,paddingTop: 7}} />}
                            onChangeTab = {(obj)=>{
                                console.log('被选中的下标:'+JSON.stringify(this.state.whskShifts[obj.i]));

                                let str = {"arg":{"opdate":this.state.whskShifts[obj.i]['opdate'],"shift":this.state.whskShifts[obj.i]['shift']}};
                                dispatch(retrieveWHSKShiftsArrangeDefault(JSON.stringify(str)));
                            }}
                        >
                            {
                                this.state.whskShifts.map((item,index)=>{
                                    return(
                                        this.showSchedule(item,index)
                                    )
                                })
                            }
                        </ScrollableTabView>

                        <Modal visible={this.state.dealPeopleVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()}>
                            <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{
                            }}>
                                <View style={styles.modalContainer}>
                                    <View style={styles.modalBox} >
                                        <View style={styles.modalTitle}>
                                            <View>
                                                <Text style={styles.modalTitleText}>
                                                    选择处理人
                                                </Text>
                                            </View>
                                            <View style={styles.modalCheck}>
                                                <Text style={styles.modalCheckText}   onPress={()=>{
                                                    let checked = '选择地点';
                                                    if(this.state.chooseDealPeople.length>0){
                                                        checked = this.state.chooseDealPeople.join(',')
                                                    }

                                                    this.onRequestClose()

                                                    let str = {"whsk_shifts_arrange":{"opdate":this.state.editInfo['opdate'],"position":this.state.editInfo['position'],"shift":this.state.editInfo['shift'],"wuserid":this.state.editInfo['wuserid'],"place":checked}}

                                                    let {dispatch} = this.props;
                                                    dispatch(shiftsArrangeEdit(JSON.stringify(str)));
                                                    // this.setState({dealPeopleVisible: false,defaultPlace:checked});
                                                }}>
                                                    确定
                                                </Text>
                                            </View>
                                        </View>
                                        <View style={styles.modalBody}>
                                            <ScrollView showsVerticalScrollIndicator={false} style={styles.modalBodyLeft}>
                                                {
                                                    this._renderRole()
                                                }
                                            </ScrollView>
                                            <ScrollView showsVerticalScrollIndicator={false} style={styles.modalBodyRight}>
                                                {
                                                    (this.state.defaultDate[this.state.chooseGroup])
                                                        ?
                                                        (

                                                            this.state.defaultDate[this.state.chooseGroup].map((item, index) => {
                                                                return this._renderDealPeopleArr(item, index)
                                                            })
                                                        )
                                                        :
                                                        (
                                                            <View>

                                                            </View>
                                                        )

                                                }
                                            </ScrollView>
                                        </View>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </Modal>


                        <Modal visible={this.state.roleSelectVisible} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()}>
                            <TouchableOpacity style={{flex: 1}} activeOpacity={1}  onPress={()=>{

                            }}>
                                <View style={styles.modalContainer}>
                                    <View style={[styles.modalBox,{height:250}]} >
                                        <View style={styles.modalTitle}>
                                            <View>
                                                <Text style={styles.modalTitleText}>
                                                    选择添加职位
                                                </Text>
                                            </View>
                                        </View>
                                        <TouchableOpacity style={styles.roleModalBody} onPress={()=>{
                                            this.onRequestClose()
                                            let reg = new RegExp("-","g");
                                            let opdate =(this.state.opdate.replace(reg,""));
                                            this.props.navigation.navigate('StaffAdd',{"shift":this.state.editInfo['shift'],"usertype":"清洁人","opdate":opdate,callBack:()=>this.returnBack()});
                                        }}>
                                            <View style={{justifyContent: 'center',alignItems: 'center',flexDirection: 'row',height:49,width:SCREEN_WIDTH}}>
                                                <Text style={{fontSize:18,color:COLOR_LINK,}}>
                                                    清洁人
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.roleModalBody} onPress={()=>{
                                            this.onRequestClose()
                                            let reg = new RegExp("-","g");
                                            let opdate =(this.state.opdate.replace(reg,""));
                                            this.props.navigation.navigate('StaffAdd',{"shift":this.state.editInfo['shift'],"usertype":"清洁检查人","opdate":opdate,callBack:()=>this.returnBack()});
                                        }}>
                                            <View style={{justifyContent: 'center',alignItems: 'center',flexDirection: 'row',height:49,width:SCREEN_WIDTH}}>
                                                <Text style={{fontSize:18,color:COLOR_LINK,}}>
                                                    清洁检查人
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.roleModalBody} onPress={()=>{
                                            this.onRequestClose()
                                            let reg = new RegExp("-","g");
                                            let opdate =(this.state.opdate.replace(reg,""));
                                            this.props.navigation.navigate('StaffAdd',{"shift":this.state.editInfo['shift'],"usertype":"对客服务","opdate":opdate,callBack:()=>this.returnBack()});
                                        }}>
                                            <View style={{justifyContent: 'center',alignItems: 'center',flexDirection: 'row',height:49,width:SCREEN_WIDTH}}>
                                                <Text style={{fontSize:18,color:COLOR_LINK,}}>
                                                    对客服务
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                        <TouchableOpacity style={styles.roleModalBody} onPress={()=>{
                                            this.onRequestClose()
                                            let reg = new RegExp("-","g");
                                            let opdate =(this.state.opdate.replace(reg,""));
                                            this.props.navigation.navigate('StaffAdd',{"shift":this.state.editInfo['shift'],"usertype":"经理","opdate":opdate,callBack:()=>this.returnBack()});
                                        }}>
                                            <View style={{justifyContent: 'center',alignItems: 'center',flexDirection: 'row',height:49,width:SCREEN_WIDTH}}>
                                                <Text style={{fontSize:18,color:COLOR_LINK,}}>
                                                    经理
                                                </Text>
                                            </View>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </TouchableOpacity>
                        </Modal>
                    </SafeAreaView>
                )
            }else{
                return (
                    <SafeAreaView style={styles.container}>
                        <View  style={styles.windowCenter}>
                            <View>
                                <Text style={styles.headerText}>
                                    暂无班次
                                </Text>
                            </View>
                            <TouchableOpacity activeOpacity={0.9} onPress={()=>{
                                this.setState({
                                    defaultInfo:{},
                                },()=>{
                                    this.freshScreen();
                                });
                            }}>
                                <View style={{marginTop:3}}>
                                    <Text style={[styles.headerText,{textDecorationLine:'underline',textDecorationStyle:'solid',fontSize:15}]}>
                                        点击添加
                                    </Text>
                                </View>
                            </TouchableOpacity>
                        </View>
                    </SafeAreaView>
                )
            }
        }
    };

    showSchedule=(item,index)=>{
        let title = item.shift;
        let tableHeader = ["值班人员","地点",""];
        let tableData = [];

        let tableData_iuser = []
        let tableData_wuser = []
        let tableData_dkfw = []
        let tableData_manager = []
        this.state.whskShifts_arrange.map((value,key)=>{
            if(value.shift === item.shift){
                let name = ''
                if(value['position'] && value['position']==="清洁人"){
                    name = (tableData_wuser.length+1)+'、'+value.describ
                }else if(value['position'] && value['position']==="清洁检查人"){
                    name = (tableData_iuser.length+1)+'、'+value.describ
                }else if(value['position'] && value['position']==="对客服务"){
                    name = (tableData_dkfw.length+1)+'、'+value.describ
                }else if(value['position'] && value['position']==="经理"){
                    name = (tableData_manager.length+1)+'、'+value.describ
                }

                let data_array = [];
                // console.log(JSON.stringify(value))
                let place_html = (
                    <Text style={styles.place_html} numberOfLines={1} onPress={()=>{
                        this.setState({
                            editInfo:value,
                            chooseDealPeople:value.place.split(','),
                            dealPeopleVisible:true,
                        })
                    }}>{value.place_c}</Text>
                );
                let describ_html = (
                    <Text style={styles.describ_html} >{name}</Text>
                );
                let opretion_html = (
                    <AntDesign name={'closecircle'} size={18} style={{color: '#d7d7d7', textAlign:'right',marginRight: 10}} onPress={()=>{
                        let str = {"whsk_shifts_arrange":{"wuserid":value.wuserid,"shift":value.shift,"opdate":value.opdate,"position":value.position}};
                        let {dispatch} = this.props;
                        dispatch(shiftsArrangeDel(JSON.stringify(str)));
                    }}/>
                );
                data_array.push(describ_html);
                data_array.push(place_html);
                data_array.push(opretion_html);

                if(value['position'] && value['position']==="清洁人"){
                    tableData_wuser.push(data_array)
                }else if(value['position'] && value['position']==="清洁检查人"){
                    tableData_iuser.push(data_array)
                }else if(value['position'] && value['position']==="对客服务"){
                    tableData_dkfw.push(data_array)
                }else if(value['position'] && value['position']==="经理"){
                    tableData_manager.push(data_array)
                }
                // tableData.push(data_array)
            }
        });


        if(tableData_wuser.length>0){
            tableData.push([<Text style={{textAlign:'left',color:FONT_COLOR_SUB_TITLE,marginLeft:3}} >清洁人</Text>]);
            tableData = tableData.concat(tableData_wuser)
        }

        if(tableData_iuser.length>0){
            tableData.push([<Text style={{textAlign:'left',color:FONT_COLOR_SUB_TITLE,marginLeft:3}} >清洁检查人</Text>]);
            tableData = tableData.concat(tableData_iuser)
        }

        if(tableData_dkfw.length>0){
            tableData.push([<Text style={{textAlign:'left',color:FONT_COLOR_SUB_TITLE,marginLeft:3}} >对客服务</Text>]);
            tableData = tableData.concat(tableData_dkfw)
        }

        if(tableData_manager.length>0){
            tableData.push([<Text style={{textAlign:'left',color:FONT_COLOR_SUB_TITLE,marginLeft:3}} >经理</Text>]);
            tableData = tableData.concat(tableData_manager)
        }

        return(
            <View tabLabel={title} style={styles.body} >
                <View style={styles.titleView}>
                    <View style={styles.titleViewLeft}>
                        <Text style={styles.titleStyle}>
                            工作时段（{item.starttime}-{item.endtime}）
                        </Text>
                    </View>

                    <TouchableOpacity style={styles.titleViewRight} onPress={()=>{
                        this.setState({
                            roleSelectVisible:true,
                        });

                    }}>
                        <Text style={styles.titleStyle}>
                            添加
                        </Text>
                    </TouchableOpacity>
                </View>

                <Table style={{marginLeft: 2}}>
                    <Row data={tableHeader} widthArr={this.state.widthArr} style={styles.tableHeader} textStyle={styles.tableText}/>
                    <Rows data={tableData} widthArr={this.state.widthArr} style={styles.tableHeader} textStyle={styles.tableText}/>
                </Table>
            </View>
        )
    };

    //打开日期选择 视图
    showPlacePicker() {
        this.setState({dealPeopleVisible:true})
    }

    onRequestClose(){
        this.setState({
            dealPeopleVisible: false,
            roleSelectVisible:false,
        })
    }

    //分组循环
    _renderRole = () => {
        let html_arr = [];

        for (let group in this.state.defaultDate){
            if(this.state.chooseGroup===""){
                this.state.chooseGroup=group
            }
            let html = (
                <TouchableOpacity  activeOpacity={1} onPress={()=>{
                    this.setState({chooseGroup:group})
                }}>
                    {this.leftBoxStyle(group)}
                </TouchableOpacity>
            )
            html_arr.push(html)
        }

        return html_arr
    };

    //判断选中分组
    leftBoxStyle(group){
        if(this.state.chooseGroup===group){
            return(
                <View style={styles.leftBoxChoose}>
                    <Text style={styles.leftText}>
                        {group}
                    </Text>
                </View>
            )
        }else{
            return(
                <View style={styles.leftBox}>
                    <Text style={styles.leftText}>
                        {group}
                    </Text>
                </View>
            )
        }
    };

    //处理人循环
    _renderDealPeopleArr = (item, index) => {
        let place = item.groupby+"."+item.code
        return(
            <TouchableOpacity key={index} activeOpacity={1} onPress={()=>{
                if(this.state.chooseDealPeople.indexOf(place)>=0){
                    this.state.chooseDealPeople.splice(this.state.chooseDealPeople.indexOf(place),1);
                }else{
                    this.state.chooseDealPeople.push(place);
                }
                this.setState({chooseDealPeople:this.state.chooseDealPeople})
            }}>
                {this.rightBoxStyle(item)}
            </TouchableOpacity>
        )
    };

    rightBoxStyle(item){
        let place = item.groupby+"."+item.code
        if(this.state.chooseDealPeople.indexOf(place)>=0){
            return(
                <View style={styles.rightBox}>
                    <MaterialCommunityIcons name={'radiobox-marked'} size={25} color={'#1f60ff'} />
                    <Text style={styles.rightTextChoose}>
                        {item.code+"层"}
                    </Text>
                </View>
            )
        }else{
            return(
                <View style={styles.rightBox}>
                    <MaterialCommunityIcons name={'radiobox-blank'} size={25} />
                    <Text style={styles.rightText}>
                        {item.code+"层"}
                    </Text>
                </View>
            )
        }
    };

}

const props = state => {
    return {
        onRetrieveWhskShiftsSetup:state.onRetrieveWhskShiftsSetup,
        onRetrieveWhskShifts:state.onRetrieveWhskShifts,
        onWHSKShiftsArrangeDefault:state.onWHSKShiftsArrangeDefault,
        onShiftsArrangeEdit:state.onShiftsArrangeEdit,
        onShiftsArrangeDel:state.onShiftsArrangeDel,
    }
};

export default StaffSchedule = connect(props)(StaffSchedule);